package com.peachcastle.core 
{
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Terry
	 */
	public class SoundData 
	{
		
		
		public var url:String;
		
		public var index:int;
		
		public var sound:Sound = null;
		
		public var iscomplete:Boolean = false;
		
		private var request:URLRequest = null;
		
		public var isplay:Boolean = false;
		
		public var channel:SoundChannel = null;
		
		private var startload:Boolean = false;
		
		private var soundTransform:SoundTransform =  null;
		
		public function SoundData(_url:String = "") 
		{
			url = _url;
			request = new URLRequest();
			request.url = url;
			
			sound = new Sound();
			
			sound.addEventListener(ProgressEvent.PROGRESS, onProgress);
			sound.addEventListener(Event.COMPLETE, onComplete);
			
			
			soundTransform = new SoundTransform();
			soundTransform.volume = 1;
			
		}
		
		public function start():void
		{
			if (isplay) return;
			isplay = true;
			if(!startload)sound.load(request);
			startload = true;
		}
		
		public function play():void
		{
			if (iscomplete)
			{
				channel = sound.play(0, 0, soundTransform);
				
				channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			}
		}
		private function onSoundComplete(event:Event):void
		{
			play();
		}
		
		public function stop():void
		{
			isplay = false;
			if (channel)
			{
				channel.stop();
				channel.removeEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			}
		}
		
		private function onProgress(event:ProgressEvent):void
		{
			//trace(event.bytesLoaded / event.bytesTotal);
		}
		private function onComplete(event:Event):void
		{
			iscomplete = true;
			
			if (isplay)
			{
				channel = sound.play(0, 0, soundTransform);
				channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
			}
			
			
		}
		
		
	}

}